package com.genghis.rapidcrm.web.view.language;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.jetwinner.common.EasyStringUtil;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

public class BaseLanguageHandler {

    protected final MessageSource messageSource;

    public BaseLanguageHandler(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String getLanguageTranslatedString(String key, String module, Locale locale) {
        return getLanguageTranslatedString(locale, key, module);
    }

    private Map<String, String> languageStringMap = new HashMap<>();

    /**
     * Function returns language specific translated string
     *
     * @param language - en_us etc
     * @param key      - label
     * @param module   - module name
     * @return <String> translated string or null if translation not found
     */
    public String getLanguageTranslatedString(Locale language, String key, String module) {
        if (EasyStringUtil.isNotBlank(module)) {
            module = module.replaceAll(":", ".");
            module = module.trim();
            String code = module + (module.endsWith(".") ? "" : ".") + key;
            try {
                return this.messageSource.getMessage(code, null, language);
            } catch (Exception e) {
                // noops.
            }
            // Lookup for the translation in base module, in case of sub modules, before ending up with common strings
            if (module.indexOf(".") > 0) {
                String baseModule = module.substring(0, module.indexOf('.'));
                if ("Settings".equals(baseModule)) {
                    baseModule = "Settings.Carpo";
                }
                code = baseModule + "." + key;
                try {
                    return this.messageSource.getMessage(code, null, language);
                } catch (Exception e) {
                    // noops.
                }
            }
        }

        try {
            return this.messageSource.getMessage(key, null, language);
        } catch (Exception e) {
            // noops.
        }

        return EasyStringUtil.isNotBlank(module) ? String.format("%s.%s", module, key) : key;
    }

    protected String export(String module, String type, Locale locale) {
        String languageCode = locale.toString() != "en" ? "_" + locale : "";
        String moduleKey = module + "/" + "tooltips" + languageCode;
        String[] keys = new String[]{moduleKey, "tooltips" + languageCode};
        StringBuilder langStr = new StringBuilder();
        boolean isFirst = true;
        for (String key : keys) {
            String value = "";
            if (!languageStringMap.containsKey(key)) {
                try {
                    Properties prop = PropertiesLoaderUtils.loadProperties(
                            new ClassPathResource(String.format("/i18n/jslang/%s.properties", key)));
                    value = new ObjectMapper().writeValueAsString(prop);
                } catch (Exception e) {
                }
                languageStringMap.put(key, value);
            }
            value = languageStringMap.get(key);
            if (EasyStringUtil.isNotBlank(value)) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    langStr.append(",");
                }
                langStr.append(value);
            }
        }
        return langStr.toString();
    }
}
